package server;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class MyClassLoader extends ClassLoader {
    
    protected Class<?> findClass(String webAppPath,String name) {
    	
    	String myPath = webAppPath+"/"+name.replaceAll("\\.","/")+".class";
//    	myPath = "C:/Users/0275632/Desktop/Minicat4/webapps/demo1/server/DemoServlet1.class";
    	System.err.println("myPath:"+myPath);
    	System.err.println("myPath1:"+myPath.replaceAll("\\\\","/"));
    	/*myPath = myPath.replaceAll("\\\\","/");
        byte[] cLassBytes = null;
        Path path = null;
        try {
            path = Paths.get(new URI(myPath));
            cLassBytes = Files.readAllBytes(path);
        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        }*/
    	
    	InputStream inputStream = null;
         ByteArrayOutputStream outputStream = null;

         try {
             inputStream = new FileInputStream(myPath);
             outputStream = new ByteArrayOutputStream();
             int temp = 0;
             while ((temp = inputStream.read()) != -1) {
                 outputStream.write(temp);
             }

         } catch (IOException e) {
             e.printStackTrace();
         }finally {
             try {
                 outputStream.close();
                 inputStream.close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }

        byte[] cLassBytes = outputStream.toByteArray();
        Class clazz = defineClass(name, cLassBytes, 0, cLassBytes.length);
        return clazz;
    }
}
